import 'dart:isolate';
import 'dart:ui';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_downloader/flutter_downloader.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:oral_cloud/config/app_config.dart';
import 'package:oral_cloud/config/constant.dart';
import 'package:oral_cloud/config/downloader_manager.dart';
import 'package:oral_cloud/config/resource_mananger.dart';
import 'package:oral_cloud/config/router_manger.dart';
import 'package:oral_cloud/config/storage_manager.dart';
import 'package:oral_cloud/generated/l10n.dart' as l10n;
import 'package:oral_cloud/model/medical_imaging.dart';
import 'package:oral_cloud/model/patient.dart';
import 'package:oral_cloud/provider/provider_widget.dart';
import 'package:oral_cloud/provider/view_state_widget.dart';
import 'package:oral_cloud/ui/page/image/medical_image_page.dart';
import 'package:oral_cloud/ui/widget/global_widget.dart';
import 'package:oral_cloud/ui/widget/image.dart';
import 'package:oral_cloud/ui/widget/imaging_list_item.dart';
import 'package:oral_cloud/ui/widget/loading_widget.dart';
import 'package:oral_cloud/view_model/medical_image_model.dart';
import 'package:oral_cloud/view_model/user_model.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'dart:io';

import 'package:photo_view/photo_view_gallery.dart';

import '../../../main.dart';

final double vSpaceOfPad = ScreenUtil.getInstance().setHeight(10);

class PatientDetailsPage extends StatefulWidget {
  final Patient patient;

  PatientDetailsPage(this.patient);
  @override
  State<StatefulWidget> createState() {
    return _PatientDetailsPageState();
  }
}

class _PatientDetailsPageState extends State<PatientDetailsPage>
    with AutomaticKeepAliveClientMixin {
  bool get wantKeepAlive => true;

  @override
  Widget build(BuildContext context) {
    super.build(context);
    print('接收参数====>patient=${widget.patient}');
    return Scaffold(
      appBar: GlobalAppBar(l10n.S.of(context).patientDetail).appBar,
      body: AppConfig.isPad
          ? PatientDetailOfPadWidget(widget.patient)
          : PatientDetailOfPhoneWidget(widget.patient),
    );
  }
}

class PatientDetailOfPhoneWidget extends StatefulWidget {
  final Patient patient;

  PatientDetailOfPhoneWidget(this.patient);
  @override
  State<StatefulWidget> createState() {
    return _PatientDetailOfPhoneWidgetState();
  }
}

class _PatientDetailOfPhoneWidgetState
    extends State<PatientDetailOfPhoneWidget> {
  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisSize: MainAxisSize.max,
      children: [
        PatientDetailsWidget(widget.patient),
        PatientImageWidget(widget.patient),
      ],
    );
  }
}

class PatientDetailOfPadWidget extends StatefulWidget {
  final Patient patient;
  final GlobalKey<RightPhotoWidgetState> rightPhotoKey = GlobalKey();

  PatientDetailOfPadWidget(this.patient);
  @override
  State<StatefulWidget> createState() {
    return _PatientDetailOfPadWidgetState();
  }
}

class _PatientDetailOfPadWidgetState extends State<PatientDetailOfPadWidget> {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Container(
      color: Color(0xfff4f4f4),
      padding: EdgeInsets.symmetric(
          horizontal: ScreenUtil.getInstance().setWidth(20),
          vertical: ScreenUtil.getInstance().setHeight(32)),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          LeftPatientDetailWidget(
            widget.patient,
            changeImages: (images, userTap) {
              print('LeftPatientDetailWidget changeImages images=$images');
              widget.rightPhotoKey.currentState?.updateImages(images, userTap);
            },
          ),
          SizedBox(
            width: ScreenUtil.getInstance().setWidth(22),
          ),
          Expanded(
            child: RightPhotoWidget(
              key: widget.rightPhotoKey,
              placeholderWidth: ScreenUtil.getInstance().setWidth(229),
              placeholderHeight: ScreenUtil.getInstance().setHeight(217),
            ),
          ),
        ],
      ),
    );
  }
}

// ignore: must_be_immutable
class RightPhotoWidget extends StatefulWidget {
  List images = [];
  String noDataHint;
  String placeholder;
  PageController controller;
  int index = 0;
  double placeholderWidth;
  double placeholderHeight;
  Color backgroudColor;
  RightPhotoWidget(
      {Key key,
      this.images,
      this.index: 0,
      this.noDataHint: '暂无影像',
      this.placeholder: 'no_image.png',
      this.placeholderWidth,
      this.placeholderHeight,
      this.backgroudColor: const Color(0XFFEAECEE)})
      : super(key: key);
  @override
  State<StatefulWidget> createState() {
    return RightPhotoWidgetState();
  }
}

class RightPhotoWidgetState extends State<RightPhotoWidget> {
  GlobalKey<SeekTextState> seekTextKey = GlobalKey();
  int currentIndex = 0;

  updateImages(List images, bool userTap) {
    print('updateImages---->images=$images,userTap=$userTap');
    if (images == null || images.isEmpty) {
      print('Should show no data!');
      return;
    }
    this.widget.images = images;
    currentIndex =
        currentIndex >= images.length ? images.length - 1 : currentIndex;
    if (!userTap) {
      Future.delayed(new Duration(milliseconds: 0), () {
        setState(() {});
      });
    } else {
      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    double photoHeight = 300;
    double photoWidth = 300;
    Widget containerWidget;
    if (widget.images == null || widget.images.isEmpty) {
      containerWidget = Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Image.asset(
              ImageHelper.wrapAssets(widget.placeholder),
              width: widget.placeholderWidth,
              height: widget.placeholderHeight,
//              height: ScreenUtil.getInstance()
//                  .setHeight(155),
//              width: ScreenUtil.getInstance()
//                  .setWidth(220),
              fit: BoxFit.cover,
            ),
            SizedBox(
              height: ScreenUtil.getInstance().setHeight(42),
            ),
            Text(
              widget.noDataHint,
              style: TextStyle(
                  color: Color(0XFFC8CACC), fontSize: FontSize.fontSizeL),
            )
          ],
        ),
      );
    } else {
      widget.controller = PageController();
      Widget photoWidget = PhotoViewGallery.builder(
        scrollPhysics: BouncingScrollPhysics(),
        builder: (BuildContext context, int index) {
          return PhotoViewGalleryPageOptions.customChild(
            child: WrapperImage(
              fit: BoxFit.contain,
              url: widget.images[index],
              placeholder: 'certificate_default.png',
            ),
            childSize: Size(photoWidth, photoHeight),
            heroAttributes: null,
          );
        },
        itemCount: widget.images.length,
        loadingChild: Container(),
        backgroundDecoration: BoxDecoration(
          color: Colors.transparent,
        ),
        pageController: widget.controller,
        enableRotation: true,
        onPageChanged: (index) {
          print('onPageChanged---->index=$index');
          currentIndex = index;
          seekTextKey?.currentState
              ?.updateCurrentIndex(index, totalLength: widget.images.length);
        },
      );
      containerWidget = Column(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          Expanded(
            child: photoWidget,
          ),
          Container(
            alignment: Alignment.center,
            width: double.infinity,
            height: ScreenUtil.getInstance().setHeight(60),
            child: SeekText(
              seekTextKey,
              widget.images.length,
              color: Color(MYColors.textNormalColor),
              currentIndex: currentIndex,
            ),
          ),
        ],
      );
    }
    return Container(
      padding: EdgeInsets.symmetric(
          horizontal: ScreenUtil.getInstance().setWidth(0),
          vertical: ScreenUtil.getInstance().setHeight(0)),
      color: widget.backgroudColor,
      child: containerWidget,
    );
  }
}

typedef ChangeImagesCallback = void Function(List images, bool userTap);

class LeftPatientDetailWidget extends StatefulWidget {
  final Patient patient;
  final ChangeImagesCallback changeImages;

  LeftPatientDetailWidget(this.patient, {this.changeImages});
  @override
  State<StatefulWidget> createState() {
    return _LeftPatientDetailWidgetState();
  }
}

class _LeftPatientDetailWidgetState extends State<LeftPatientDetailWidget> {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Container(
      color: Colors.white,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.max,
        children: [
          LeftBasicPatientDetailWidget(widget.patient),
          PatientImageWidget(
            widget.patient,
            changeImages: widget.changeImages,
          ),
        ],
      ),
      width: ScreenUtil.getInstance().setWidth(630),
      height: double.infinity,
    );
  }
}

class LeftBasicPatientDetailWidget extends StatelessWidget {
  final Patient patient;

  LeftBasicPatientDetailWidget(this.patient);

  @override
  Widget build(BuildContext context) {
    return Container(
        margin: EdgeInsets.symmetric(
            horizontal: ScreenUtil.getInstance().setWidth(
          40,
        )),
        padding: EdgeInsets.only(top: ScreenUtil.getInstance().setHeight(26)),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisSize: MainAxisSize.max,
          children: [
            Stack(
              alignment: Alignment.bottomRight,
              children: [
                ClipOval(
                  child: WrapperImage(
                    imageType: ImageType.normal,
                    url: patient.avatar,
                    placeholder: patient.sex == 1
                        ? 'male_default.png'
                        : 'female_default.png',
                    height: ScreenUtil.getInstance().setWidth(80),
                    width: ScreenUtil.getInstance().setWidth(80),
                  ),
                ),
                Image.asset(
                  ImageHelper.wrapAssets(
                      patient.sex == 1 ? 'male.png' : 'female.png'),
                  width: ScreenUtil.getInstance().setWidth(25),
                  height: ScreenUtil.getInstance().setWidth(25),
                )
              ],
            ),
            Expanded(
              child: Padding(
                padding: EdgeInsets.only(
                    right: ScreenUtil.getInstance().setWidth(20),
                    left: ScreenUtil.getInstance().setWidth(20),
                    bottom: ScreenUtil.getInstance().setHeight(62)),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        NormalText('姓名: ${patient.username}'),
                        NormalText(patient.sex == 1 ? '男' : '女'),
                      ],
                    ),
                    SizedBox(height: vSpaceOfPad),
                    NormalText('患者编号:${patient.patientNo}'),
                    SizedBox(height: vSpaceOfPad),
                    NormalText('出生日期:${patient.birthDate}'),
                    SizedBox(height: vSpaceOfPad),
                    NormalText('录入日期:${patient.recordDate}'),
                    SizedBox(height: vSpaceOfPad),
                    NormalText('联系电话:${patient.mobile}'),
                    SizedBox(height: vSpaceOfPad),
                    NormalText('联系地址:${patient.address}'),
                    SizedBox(height: vSpaceOfPad),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        NormalText('CT：${patient.ctNum}'),
                        NormalText('局部CT：${patient.partCtNum}'),
                        NormalText('全景：${patient.panoramicNum}'),
                      ],
                    ),
                    SizedBox(height: vSpaceOfPad),
                    Row(
                      children: [
                        NormalText('侧位：${patient.lateralNum}'),
                        SizedBox(width: ScreenUtil.getInstance().setWidth(115)),
                        NormalText('TMJ：${patient.tmjNum}'),
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
        decoration: BoxDecoration(
          border: Border(
            bottom: BorderSide(
              width: 0.5,
              color: Color(0xffE6E6E6),
            ),
          ),
        ));
  }
}

// ignore: must_be_immutable
class PatientImageWidget extends StatefulWidget {
  final Patient patient;
  ChangeImagesCallback changeImages;
  List<dynamic> list;
  int selectIndex = 0;
  PatientImageWidget(this.patient, {this.changeImages});
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _PatientImageWidgetState();
  }
}

class _PatientImageWidgetState extends State<PatientImageWidget> {
  static const String PORT_NAME = 'downloader_send_port';
  DownloaderMgr _downloaderMgr;
  ReceivePort _port = ReceivePort();
  @override
  void initState() {
    initData();
    super.initState();
  }

  @override
  void dispose() {
    _unbindBackgroundIsolate();
    super.dispose();
  }

  void _bindBackgroundIsolate() {
    bool isSuccess =
        IsolateNameServer.registerPortWithName(_port.sendPort, PORT_NAME);
    if (!isSuccess) {
      _unbindBackgroundIsolate();
      _bindBackgroundIsolate();
      return;
    }
    _port.listen((dynamic data) async {
      print('UI Isolate Callback: $data');

      String id = data[0];
      DownloadTaskStatus status = data[1];
      final MedicalImaging task = widget.list?.firstWhere((task) {
        print('UI Isolate Callback task.group: ${task.group}');
        return task.group == id;
      });
      if (task == null) {
        return;
      }
      if (status == DownloadTaskStatus.complete ||
          status == DownloadTaskStatus.failed) {
        List<dynamic> taskList = await FlutterDownloader.loadTasksWithRawQuery(
            query: "SELECT * FROM task WHERE id='$id' ");
        int totalLength = task.imageList.length;
        print('_bindBackgroundIsolate taskList.length=${taskList.length}');
        if (taskList.length == 0) {
          task.status = DownloadTaskStatus.undefined;
          setState(() {});
          return;
        }
        //表示异步未查询到所有的下载任务
        if (taskList.length != totalLength) {
          return;
        }
        if (status == DownloadTaskStatus.failed) {
          task.status = DownloadTaskStatus.failed;
          for (DownloadTask task in taskList) {
            if (task.status == DownloadTaskStatus.enqueued ||
                task.status == DownloadTaskStatus.running||task.status == DownloadTaskStatus.failed) {
              _downloaderMgr.removeDownload(task.taskId);
            }
          }
          setState(() {});
          return;
        }

        int successCount = 0;
        int failCount = 0;
        int runningCount = 0;
        for (DownloadTask task in taskList) {
          if (task.status == DownloadTaskStatus.complete) {
            successCount++;
          } else if (task.status == DownloadTaskStatus.running) {
            runningCount++;
          }
        }
        print(
            '_bindBackgroundIsolate successCount:$successCount,failCount:$failCount,runningCount:$runningCount,totalLength=$totalLength,taskList.length=${taskList.length}');
        if (successCount == totalLength) {
          task.status = DownloadTaskStatus.complete;
        } else if (runningCount > 0) {
          task.status = DownloadTaskStatus.running;
          double percent = 100 * (1.0 * successCount) / totalLength;
          task.progress = percent.toInt();
        }
        setState(() {});
      }
//      String taskId = data[0];
//      DownloadTaskStatus status = data[1];
//      int progress = data[2];
//      if(status==DownloadTaskStatus.running&&progress<0){
//        return;
//      }
//      final task = widget.list?.firstWhere((task) {
//        print('UI Isolate Callback task.taskId: ${task.taskId},id=$id');
//        return task.taskId == id;
//      });
//      print('UI Isolate Callback task: $task');
//      if (task != null) {
//        if (status == DownloadTaskStatus.complete) {
//          final tasks = await FlutterDownloader.loadTasksWithRawQuery(
//              query: "SELECT * FROM task WHERE task_id='$id' ");
//          if (tasks != null && tasks.length == 1) {
//            if (task is MedicalImaging) {
//              print(
//                  'UI Isolate Callback tasks[0].savedDir: ${tasks[0].savedDir}');
//              task.savedDir = tasks[0].savedDir;
//              task.filename = tasks[0].filename;
//            }
//          }
//        }
//
//        setState(() {
//          task.status = status;
//          task.progress = progress;
//        });
//      }
    });
  }

  void _unbindBackgroundIsolate() {
    IsolateNameServer.removePortNameMapping(PORT_NAME);
  }

  static void downloadCallback(
      String taskId, DownloadTaskStatus status, int progress) {
    print(
        'Background Isolate Callback: task ($taskId) is in status ($status) and process ($progress)');
    final SendPort send = IsolateNameServer.lookupPortByName(PORT_NAME);
    send.send([taskId, status, progress]);
  }

  initData() async {
    _bindBackgroundIsolate();
    FlutterDownloader.registerCallback(downloadCallback);
    String localPath =
        (await _findLocalPath()) + Platform.pathSeparator + 'Download';
    _downloaderMgr = DownloaderMgr(localPath);
    _downloaderMgr.prepare();
  }

  Future<String> _findLocalPath() async {
    final directory = StorageManager.platform == TargetPlatform.android
        ? await getExternalStorageDirectory()
        : await getApplicationDocumentsDirectory();
    return directory.path;
  }

  Future<bool> _checkPermission(BuildContext context) async {
    if (Platform.isAndroid) {
      PermissionStatus permission = await PermissionHandler()
          .checkPermissionStatus(PermissionGroup.storage);
      if (permission != PermissionStatus.granted) {
        Map<PermissionGroup, PermissionStatus> permissions =
            await PermissionHandler()
                .requestPermissions([PermissionGroup.storage]);
        if (permissions[PermissionGroup.storage] == PermissionStatus.granted) {
          return true;
        }
      } else {
        return true;
      }
    } else {
      return true;
    }
    return false;
  }

  @override
  Widget build(BuildContext context) {
    String token = UserModel().user.token;
    List<Widget> children = [];
    Widget headWidget;
    if (AppConfig.isPad) {
      headWidget = Padding(
          padding: EdgeInsets.symmetric(
              vertical: ScreenUtil.getInstance().setHeight(16)),
          child: Text(
            l10n.S.of(context).patientImg,
            style:
                TextStyle(color: Colors.black, fontSize: FontSize.fontSizeXL),
          ));
    } else {
      headWidget = UnderLineText(
        l10n.S.of(context).patientImg,
        height: ScreenUtil.getInstance().setHeight(76),
      );
    }
    return ProviderWidget<MedicalImageModel>(
      model: MedicalImageModel(token, widget.patient.id),
      onModelReady: (model) {
        model.initData();
      },
      builder: (context, model, child) {
        children.clear();
        children.add(headWidget);
        if (model.isBusy) {
          children.add(Expanded(
            child: LoadingWidget(),
          ));
        } else if (model.isError) {
          children.add(Expanded(
            child: ViewStateErrorWidget(
              error: model.viewStateError,
              onPressed: model.initData,
            ),
          ));
        } else if (model.isEmpty) {
          if (widget.changeImages != null) {
            widget.changeImages(null, false);
          }
          children.add(Container(
            padding:
                EdgeInsets.only(top: ScreenUtil.getInstance().setHeight(22)),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Image.asset(
                  ImageHelper.wrapAssets('image_default.png'),
                  height: ScreenUtil.getInstance()
                      .setHeight(AppConfig.patientImgItemImageHeight),
                  width: ScreenUtil.getInstance()
                      .setWidth(AppConfig.patientImgItemImageWidth),
                ),
                SizedBox(
                  width: ScreenUtil.getInstance()
                      .setWidth(AppConfig.patientImgItemImageMarginRight),
                ),
                Text(
                  l10n.S.of(context).noData,
                  style: TextStyle(
                    color: Color(MYColors.textHighlightColor),
                    fontSize: FontSize.fontSizeL,
                  ),
                )
              ],
            ),
          ));
        } else if (model.isIdle) {
          widget.list = model.list;
          MedicalImaging imaging = model.list[0];
          if (widget.changeImages != null) {
            widget.changeImages(imaging.imageList, false);
          }
          children.add(Expanded(
            child: ImageListWidget(
              model.list,
              imageItemTap: (tapType, index) async {
                print('tapType=$tapType,index=$index');
                MedicalImaging imaging = model.list[index];
                if (tapType == ImageItemTapType.tapTypeDownload ||
                    tapType == ImageItemTapType.tapTypeRetry) {
                  imaging.reqStatus = MedicalImageStatus.progressing;
                  setState(() {});
                  List<dynamic> downloadUrls =
                      await model.fetchImgDownloadUrl(token, imaging.group);
                  print('downloadUrls=$downloadUrls');
                  if (downloadUrls == null) {
                    imaging.reqStatus = MedicalImageStatus.failed;
                    setState(() {});
                  } else {
                    List<dynamic> taskList =
                        await FlutterDownloader.loadTasksWithRawQuery(
                            query:
                                "SELECT * FROM task WHERE id='${imaging.group}' and status=3");
                    print('taskList=${taskList.length}');
                    for (var url in downloadUrls) {
                      bool isSkip = false;
                      for (DownloadTask task in taskList) {
                        if (task.url == url) {
                          isSkip = true;
                          break;
                        }
                      }
                      if (isSkip) {
                        continue;
                      }
                      TaskInfo taskInfo = TaskInfo();
                      taskInfo.link = url;
                      taskInfo.id = imaging.group;
                      taskInfo.taskId =
                          await _downloaderMgr.startDownload(taskInfo);
                    }
                    imaging.reqStatus = MedicalImageStatus.completed;
                    imaging.status = DownloadTaskStatus.running;
                    setState(() {});
                  }
                } else if (tapType == ImageItemTapType.tapTypeJump) {
                  bool hasPermission = await _checkPermission(context);
                  if (hasPermission) {
                    imaging.savedDir = _downloaderMgr.localPath +
                        Platform.pathSeparator +
                        imaging.group+Platform.pathSeparator;
                    _jumpTo3DPriview(imaging.savedDir);
                  }
                } else if (tapType == ImageItemTapType.tapTypeItem) {
                  print('itemTap===>ImagingItemWidget');
                  if (AppConfig.isPad) {
                    widget.changeImages(imaging.imageList, true);
                  } else {
                    Navigator.of(context).pushNamed(RouteName.medical_image,
                        arguments: imaging.imageList);
                  }
                } else if (tapType == ImageItemTapType.tapTypePause) {
//                  _downloaderMgr.pauseDownload(imaging);
                } else if (tapType == ImageItemTapType.tapTypeResume) {
//                  _downloaderMgr.resumeDownload(imaging);
                } else if (tapType == ImageItemTapType.tapTypeCancel) {
                  List<dynamic> taskList =
                      await FlutterDownloader.loadTasksWithRawQuery(
                          query:
                              "SELECT * FROM task WHERE id='${imaging.group}'");
                  for (DownloadTask task in taskList) {
                    print('cancelDownload task=${task.toString()}');
                    _downloaderMgr.removeDownload(task.taskId);
                  }
                  setState(() {
                    imaging.progress = 0;
                    imaging.reqStatus = MedicalImageStatus.undefined;
                    imaging.status = DownloadTaskStatus.undefined;
                  });
                }
              },
            ),
          ));
          if (!AppConfig.isPad) {
            children.add(Container(
              width: double.infinity,
              alignment: Alignment.center,
              height: ScreenUtil.getInstance().setHeight(134),
              child: NormalText(
                  '共${model.list.length}组数据，${totalCount(model.list)}帧影像'),
            ));
          }
        }
        return Expanded(
          child: Container(
            padding: EdgeInsets.only(
              left: ScreenUtil.getInstance().setWidth(40),
              right: ScreenUtil.getInstance().setWidth(40),
              top: ScreenUtil.getInstance().setHeight(22),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: children,
            ),
          ),
        );
      },
    );
  }

  _jumpTo3DPriview(String dcmPath) {
    print('dcmPath=$dcmPath');
    Map<String, String> map = {'dcmPath': dcmPath};
    platform.invokeMethod('jump2VTK3DView', map);
  }

  int totalCount(List<dynamic> list) {
    int totalCount = 0;
    if (list == null || list.isEmpty) {
      return 0;
    }
    for (MedicalImaging image in list) {
      totalCount += image.count;
    }
    return totalCount;
  }
}

class ImageListWidget extends StatefulWidget {
  ImageItemTapCallback imageItemTap;
  List<dynamic> list;
  int selectIndex;
  ImageListWidget(this.list, {this.imageItemTap, this.selectIndex: 0});
  @override
  State<StatefulWidget> createState() {
    return _ImageListWidgetState();
  }
}

class _ImageListWidgetState extends State<ImageListWidget> {
  updateSelectIndex(int selectIndex) {
    setState(() {
      this.widget.selectIndex = selectIndex;
    });
  }

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
        itemCount: widget.list.length,
        itemBuilder: (context, index) {
          MedicalImaging imaging = widget.list[index];
          return AppConfig.isPad
              ? ImagingItemWidgetOfPad(
                  imaging,
                  index: index,
                  isSelected: widget.selectIndex == index,
                  itemTap: (tapType, index) {
                    print('ImagingItemWidgetOfPad---->itemTap');
                    widget.imageItemTap(tapType, index);
                    if (tapType == ImageItemTapType.tapTypeItem) {
                      updateSelectIndex(index);
                    }
                  },
                )
              : ImagingItemWidget(
                  imaging,
                  index: index,
                  itemTap: widget.imageItemTap,
                );
        });
  }
}

class PatientDetailsWidget extends StatelessWidget {
  final Patient patient;

  PatientDetailsWidget(this.patient);
  @override
  Widget build(BuildContext context) {
    return Container(
        padding: EdgeInsets.only(
            left: ScreenUtil.getInstance().setWidth(42),
            top: ScreenUtil.getInstance().setHeight(42)),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisSize: MainAxisSize.max,
          children: [
            Stack(
              alignment: Alignment.bottomRight,
              children: [
                ClipOval(
                  child: WrapperImage(
                    imageType: ImageType.normal,
                    url: patient.avatar,
                    placeholder: patient.sex == 1
                        ? 'male_default.png'
                        : 'female_default.png',
                    height: ScreenUtil.getInstance().setWidth(126),
                    width: ScreenUtil.getInstance().setWidth(126),
                  ),
                ),
                Image.asset(
                  ImageHelper.wrapAssets(
                      patient.sex == 1 ? 'male.png' : 'female.png'),
                  width: ScreenUtil.getInstance().setWidth(40),
                  height: ScreenUtil.getInstance().setWidth(40),
                )
              ],
            ),
            Expanded(
              child: Padding(
                padding: EdgeInsets.only(
                    right: ScreenUtil.getInstance().setWidth(42),
                    left: ScreenUtil.getInstance().setWidth(42),
                    bottom: ScreenUtil.getInstance().setWidth(34)),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '姓名:${patient.username}',
                      style: TextStyle(
                        fontWeight: FontWeight.bold,
                        color: Color(MYColors.textHighlightColor),
                        fontSize: FontSize.fontSizeL,
                      ),
                    ),
                    SizedBox(height: ScreenUtil.getInstance().setWidth(22)),
                    MultiNormalText('患者编号:${patient.patientNo}'),
                    VSpaceWidget(),
                    Row(
                      children: [
                        NormalText('出生日期:${patient.birthDate}'),
                        HSpaceWidget(),
                        NormalText('录入日期:${patient.recordDate}'),
                      ],
                    ),
                    VSpaceWidget(),
                    NormalText('联系电话:${patient.mobile}'),
                    VSpaceWidget(),
                    MultiNormalText('联系地址:${patient.address}'),
                    VSpaceWidget(),
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        NormalText('CT：${patient.ctNum}'),
                        HSpaceWidget(),
                        NormalText('局部CT：${patient.partCtNum}'),
                        HSpaceWidget(),
                        NormalText('全景：${patient.panoramicNum}'),
                        HSpaceWidget(),
                        NormalText('侧位：${patient.lateralNum}'),
                        HSpaceWidget(),
                        NormalText('TMJ：${patient.tmjNum}'),
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
        decoration: BoxDecoration(
          border: Border(
            bottom: BorderSide(
              width: 10,
              color: Color(0xffeef5f9),
            ),
          ),
        ));
  }

  int countImagingByType(int type, List<MedicalImaging> imagings) {
    int count = 0;
    if (imagings == null || imagings.isEmpty) {
      return 0;
    }
    for (var imaging in imagings) {
      if (imaging.type == type) {
        count++;
      }
    }
    return count;
  }
}

class VSpaceWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return SizedBox(height: ScreenUtil.getInstance().setHeight(20));
  }
}

class HSpaceWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return SizedBox(width: ScreenUtil.getInstance().setWidth(36));
  }
}
